class ChatManager {
    constructor() {
        this.chatMessages = document.querySelector('.chat-messages');
        this.chatInput = document.querySelector('.chat-input input');
        this.sendButton = document.querySelector('.chat-input button');
        this.messages = [];
        
        // 配置API地址
        this.API_URL = 'http://localhost:5000/api/chat';
        
        this.initializeEventListeners();
        this.loadChatHistory();
        this.checkAPIConnection();
    }

    initializeEventListeners() {
        // 发送消息事件
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });
    }

    async loadChatHistory() {
        try {
            const history = await this.fetchChatHistory();
            this.messages = history;
            this.renderMessages();
        } catch (error) {
            console.error('加载聊天历史失败:', error);
            // 添加系统欢迎消息
            this.addMessage({
                type: 'system',
                content: '欢迎来到您的数字生命空间！我是您的数字助手林婉儿，让我们开始对话吧。',
                timestamp: new Date()
            });
        }
    }

    async sendMessage() {
        const content = this.chatInput.value.trim();
        if (!content) return;

        // 添加用户消息
        this.addMessage({
            type: 'user',
            content,
            timestamp: new Date()
        });

        this.chatInput.value = '';
        this.chatInput.focus();

        try {
            // 获取AI响应
            const response = await this.getAIResponse(content);
            this.addMessage({
                type: 'ai',
                content: response,
                timestamp: new Date()
            });
        } catch (error) {
            console.error('获取AI响应失败:', error);
            this.addMessage({
                type: 'system',
                content: '抱歉，我暂时无法回应，请稍后再试。',
                timestamp: new Date()
            });
        }
    }

    async checkAPIConnection() {
        try {
            const response = await fetch(this.API_URL, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            if (response.ok) {
                console.log('API连接正常');
            } else {
                console.error('API连接异常:', response.status);
            }
        } catch (error) {
            console.error('API连接失败:', error);
        }
    }

    async getAIResponse(message) {
        try {
            console.log('Sending request to:', this.API_URL);
            const response = await fetch(this.API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                mode: 'cors',
                credentials: 'omit',
                body: JSON.stringify({
                    message: message
                })
            });

            console.log('Response status:', response.status);
            const data = await response.json();
            console.log('Response data:', data);

            if (!response.ok) {
                throw new Error(data.error || 'API请求失败');
            }

            if (!data.success) {
                throw new Error(data.error || 'API响应错误');
            }

            return data.response;

        } catch (error) {
            console.error('API调用失败:', error);
            throw error;
        }
    }

    addMessage(message) {
        this.messages.push(message);
        this.renderMessage(message);
        this.scrollToBottom();
        this.saveChatHistory();
    }

    renderMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.className = `message ${message.type}`;
        
        const time = new Date(message.timestamp).toLocaleTimeString();
        
        messageElement.innerHTML = `
            <div class="message-content">
                <div class="message-text">${message.content}</div>
                <div class="message-time">${time}</div>
            </div>
        `;

        this.chatMessages.appendChild(messageElement);
    }

    renderMessages() {
        this.chatMessages.innerHTML = '';
        this.messages.forEach(message => this.renderMessage(message));
        this.scrollToBottom();
    }

    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    // 本地存储聊天历史
    saveChatHistory() {
        try {
            localStorage.setItem('chatHistory', JSON.stringify(this.messages));
        } catch (error) {
            console.error('保存聊天历史失败:', error);
        }
    }

    // 从本地存储加载聊天历史
    async fetchChatHistory() {
        const history = localStorage.getItem('chatHistory');
        return history ? JSON.parse(history) : [];
    }
}

// 创建聊天管理器实例
window.chatManager = new ChatManager(); 